﻿<%@ WebHandler Language="C#" Class="SysSerialNumMgr" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;

public class SysSerialNumMgr : AjaxHandlerBase
{
    public SysSerialNumMgr()
    {
        htTypePermit.Add("add", Constants.Permit_SerialNumber_Add);
        htTypePermit.Add("edit", Constants.Permit_SerialNumber_Edit);
        htTypePermit.Add("handler", Constants.Permit_SerialNumber_Op);
        htTypePermit.Add("del", Constants.Permit_SerialNumber_Del);
    }

    override public void RequestProcess(HttpContext context)
    {
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "getlist":     //页面查询结果集Table
                strResponse= getlist(context);
                break;
            case "add":         //添加授权
               strResponse= add(context);
                break;
            case "edit":        //修改授权
               strResponse= edit(context);
                break;
            case "handler":        //激活/禁用授权
                strResponse = operation(context);
                break;
            case "getmodel":        //根据主键返回该条记录数据
                strResponse = getmodel(context);
                break;
            case "del":         //删除授权
                strResponse = del(context);
                break;
            default:
                break;
        }
        context.Response.ContentType = "text/plain";
        context.Response.Buffer = true;
        context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        context.Response.Write(strResponse);
    }
    
    

    //删除授权
    private string del(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];
            Chenxin.Lib.Passport.DAL.System_SerialNumber.Delete(new Guid(modelid));

            //添加记录
            AddLog("" + CurrentUserInfo.UserName + "删除授权",
                    OperationType.OperationTypeComboList()["OprType_SerialNumDel"].ToString());

            return string.Format("{{success:'1',msg:'{0}',data:''}}", "删除成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
    
    //根据id得到单条记录
    private string getmodel(HttpContext context)
    {
        string modelid = context.Request.Params["modelid"];
        Chenxin.Lib.Passport.Entity.System_SerialNumber ds;
        try
        {
            ds = Chenxin.Lib.Passport.DAL.System_SerialNumber.GetModel(new Guid(modelid));               
            if (ds == null)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，找不到对应的部门参数");
            }
            return string.Format("{{success:'1',msg:'成功',data:{{model:{0}}}}}",
                 Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", ex.Message);
        }    
    }
    
    //查询结果集
    private string getlist(HttpContext context)
    {
        string selCity = context.Request.Params["cityid"];
        string selCompany = context.Request.Params["companyid"];
        string selDepart = context.Request.Params["depart"];
        string selUser = context.Request.Params["username"];
        string selMacAddress = context.Request.Params["macaddress"];
        
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (selCompany != "" && selCompany != "请选择" && selCompany != null)
            sb.AppendFormat(" AND CompanyId = '{0}'", selCompany);
        else if (selCity != "" && selCity != "请选择" && selCity != null)
            sb.AppendFormat(" AND CityId = '{0}'", selCity);
        else
            sb.AppendFormat(" AND CompanyId = '{0}'", CurrentUserInfo.CompanyId.ToString());


        System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
        //查看权限
        //所有
        if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllSerialNumber))
        {
            sb1.Append(" (1=1) ");
        }
        //城市
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCitySerialNumber))
        {
            sb1.Append(string.Format("  CityId = '{0}' ", CurrentUserInfo.CityId.ToString()));
        }
        //公司
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanySerialNumber))
        {
            sb1.Append(string.Format("  CompanyId = '{0}' ", CurrentUserInfo.CompanyId.ToString()));
        }
        //没有权限
        else
        {
            sb1.Append(" (1=0) ");
        }

        if (!String.IsNullOrEmpty(sb.ToString()))
            sb1.Append(sb.ToString());
        if (selDepart != "" && selDepart != null)
        {
            sb1.Append("and Depart like '" + selDepart + "%'");
        }
        if (selUser != "" && selUser != null)
        {
            sb1.Append("and UserName like '" + selUser + "%'");
        }
        if (!string.IsNullOrEmpty(selMacAddress))
        {
            sb1.Append("and MacAddress like '%" + selMacAddress + "%'");
        }

        int PageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
        int PageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
        string fieldlist = "SerialNumber,MACAddress,City,Company,Depart,UserName,ConstractPhone,Status,Addtime";
        string fieldtablelist = "SerialNumber,MACAddress,City,Company,Depart,UserName,ConstractPhone,CASE WHEN Status='1' THEN '有效' ELSE '无效' END as Status,convert(char,Addtime,23) AS Addtime";
        string orderfield = "System_SerialNumber.Addtime desc";

        DataSet ds = Chenxin.Lib.Passport.DAL.System_SerialNumber.GetList(PageIndex, PageSize, orderfield, "System_SerialNumber", sb1.ToString(), fieldlist,fieldtablelist, true);
        int count = (int)ds.Tables[1].Rows[0][0];
        string strHtml = "";
        if (!GetKeyListHtml(ds, out strHtml))
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml);
        }
        ds.Dispose();
        ds = null;
        return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
    }

    //生成部门列表的HTML
    private bool GetKeyListHtml(DataSet dslist, out string strHtml)
    {
        try
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
            sb.Append("<thead><tr>");
            sb.Append("<th width=\"60px\">城市</th>");
            sb.Append("<th width=\"60px\">公司</th>");
            sb.Append("<th width=\"60px\" >部门</th>");
            sb.Append("<th width=\"80px\" >使用人</th>");
            sb.Append("<th>授权号</th>");
            sb.Append("<th width=\"100px\">电话</th>");
            sb.Append("<th width=\"60px\">状态</th>");
            sb.Append("<th width=\"120px\">添加时间</th>");
            sb.Append("</tr></thead><tbody>");

            foreach (DataRow row in dslist.Tables[0].Rows)
            {
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\" >", row["SerialNumber"].ToString(), "");
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "City", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Company", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Depart", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "UserName", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "MACAddress", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ConstractPhone", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Status", ""));
                sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Addtime", ""));
                sb.Append("</tr>");
            }
            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }

    //添加授权
    private string add(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Passport.Entity.System_SerialNumber model = (Chenxin.Lib.Passport.Entity.System_SerialNumber)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.Passport.Entity.System_SerialNumber));
            model.SerialNumber = Guid.NewGuid();
            model.City = model.OprCity = CurrentUserInfo.CityName;
            model.CityId = model.OprCityId = CurrentUserInfo.CityId;
            model.Company = model.OprCompany = CurrentUserInfo.CompanyName;
            model.OprCompanyId = model.CompanyId = CurrentUserInfo.CompanyId;
            model.Status = 1;
            model.OprDepart = CurrentUserInfo.DepartName;
            model.OprDepartId = CurrentUserInfo.DepartId;
            model.OprPerson = CurrentUserInfo.UserName;
            model.OprPersonId = CurrentUserInfo.UserId;
            model.Addtime = DateTime.Now;
           // model.MACAddress = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(model.MACAddress, "MD5");

            if (!Chenxin.Lib.Passport.DAL.System_SerialNumber.CheckExist(model.MACAddress))
            {
                Chenxin.Lib.Passport.DAL.System_SerialNumber.Add(model);

                //添加记录
                AddLog("" + CurrentUserInfo.UserName + "新增授权：" + model.Depart + "[" + model.UserName + "]",
                        OperationType.OperationTypeComboList()["OprType_SerialNumAdd"].ToString());

                return string.Format("{{success:'1',msg:'{0}',data:''}}", "新增成功！");
            }
            else
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "新增失败，该授权号已存在！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }

    //编辑授权
    private string edit(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Passport.Entity.System_SerialNumber model = (Chenxin.Lib.Passport.Entity.System_SerialNumber)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.Passport.Entity.System_SerialNumber));

            
            
            string mac = context.Request.Params["oldmac"];
            
            bool flag = false;

            if (mac != model.MACAddress)
                flag = Chenxin.Lib.Passport.DAL.System_SerialNumber.CheckExist(model.MACAddress);
            if (!flag)
            {
                //model.MACAddress = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(model.MACAddress, "MD5");
                Chenxin.Lib.Passport.DAL.System_SerialNumber.Update(model);

                AddLog("" + CurrentUserInfo.UserName + "编辑授权：" + model.Depart + "[" + model.UserName + "]",
                        OperationType.OperationTypeComboList()["OprType_SerialNumEdit"].ToString());

                return string.Format("{{success:'1',msg:'{0}',data:''}}", "编辑成功！");
            }
            else
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "编辑失败，该授权号已存在！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
    
    //激活/禁用授权
    private string operation(HttpContext context)
    {
        try
        {
            string modelid = context.Request["modelid"];
            string status = context.Request["status"];
            string strSql = string.Format("update System_SerialNumber set status='{0}' where SerialNumber='{1}'", status, modelid);
            Chenxin.Lib.Passport.DAL.System_SerialNumber.ExecuteSQL(strSql);

            Chenxin.Lib.Passport.Entity.System_SerialNumber model = Chenxin.Lib.Passport.DAL.System_SerialNumber.GetModel(new Guid(modelid));
            if (status == "0")
            {
                AddLog("" + CurrentUserInfo.UserName + "激活授权：" + model.Depart + "[" + model.UserName + "]",
                    OperationType.OperationTypeComboList()["OprType_SerialNumActive"].ToString());

                return string.Format("{{success:'1',msg:'{0}',data:''}}", "禁用成功！");
            }
            else
            {
                AddLog("" + CurrentUserInfo.UserName + "禁用授权：" + model.Depart + "[" + model.UserName + "]",
                    OperationType.OperationTypeComboList()["OprType_SerialNumStop"].ToString());
                return string.Format("{{success:'1',msg:'{0}',data:''}}", "激活成功！");
            }
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
}